package com.shop.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.util.Properties;

/**
 * @author XCH
 * @date 2025 - 06 - 19
 */
@Configuration
public class RedisConfig {
    @Bean
    public JedisPoolConfig jedisPoolConfig() throws IOException {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(20);
        poolConfig.setMaxTotal(100);
        return poolConfig;
    }



    /**
     * 配置Redis连接工厂 (Jedis)
     */
    @Bean
    public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig poolConfig) throws Exception {
        Properties prop = new Properties();
        prop.load(new ClassPathResource("redis.properties").getInputStream());

        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setPoolConfig(jedisPoolConfig());//注入连接池配置

        return factory;
    }

    /**
     * 配置RedisTemplate，并设置序列化器
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) throws Exception {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // key 使用String序列化
        template.setKeySerializer(new StringRedisSerializer());

        // 注册Java 8时间模块
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule()); // 注册Java8时间模块
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 禁用时间戳格式

        // value 使用JSON序列化
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        serializer.setObjectMapper(objectMapper); // 通过 setObjectMapper 设置自定义的 mapper

        template.setValueSerializer(serializer);
        template.setHashKeySerializer(serializer);
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet(); // 初始化模板配置
        return template;
    }

    @Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) throws Exception {
    return new StringRedisTemplate(factory);
}

}